<?php
namespace App\Http\Controllers\Front;

use App\Models\Comments;
use App\Models\CompanyComment;
use App\Models\EmployComments;
use App\Models\EmployExt;
use App\Models\Courses;
use App\Models\CourseScore;
use App\Models\BbsQuestion;
use App\Models\BbsAnswer;
use App\Models\BbsAnswerComment;
use App\Models\Teaches;
use App\Models\TeachesCompany;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\TeachesContent;
use App\Models\SystemSetting;
use Illuminate\Support\Facades\Log;
use App\Models\Company;
use App\Models\CompanyJobs;


class CommentController extends MasterController
{
    private $infos;
    public function __construct(){
        $systemSetting = new SystemSetting();
        $this->infos = $systemSetting->getSetting("index");
    }
    /**
     * 评论列表
     */
    public function comment(Request $request)
    {
        $typeid = $request->input('typeid',0);  // 1：企业评论(公司、职位) 2:课程评分 3：就业指南  4： 社区  5：其他模块(职场教程、企业内训)
        switch ($typeid)
        {
            case 1:
                return  $this->comcom();
            case 2:
                return  $this->coursecom();
            case 3:
                return  $this->empcom();
            case 4:
                return  $this->bbscom();
            default:
                return  $this->teachescom();
        }
    }

    /**
     * 企业评论 ：企业评论 或 职位评论
     */
    private function comcom()
    {
        $user = Auth::user();
        if(empty($user)){
            return  Response::json(array('msg'=>'请先登录！',
                'status'=>'falses',
            ));
        }
        $company = Company::find(Input::get('comid',0));
        if(empty($company))
        {
            return $this->formatJson('error','评论失败，未找到相关企业！');
        }
        $jobsid = Input::get('jid',0);
        if(!empty($jobsid) && $jobsid > 0)
        {
            $jobs = CompanyJobs::where(['company_id'=>$company->id,'jobs_id'=>Input::get('jid',0)])->first();
            if(empty($jobs))
                return $this->formatJson('error','参数错误！');
        }
        $comment = new CompanyComment;
        $comment->company_id = $company->id;
        $comment->job_id = $jobsid;
        $comment->user_id = $user->id;
        $comment->content = Input::get('content');
        $comment->to_comment_id = Input::get('cid',0);
        $comment->to_user_id = Input::get('touid',0);
        //敏感词过滤
        $wordstr = $this->infos['sensitive_words'];
        $comment->content = $this->filterWords(Input::get('content'),$wordstr);
        if(empty($comment->content))
        {
            return  Response::json(array('msg'=>'评论内容不能为空！',
                'status'=>'falses',
            ));
        }else{
            try {
                $comment->save();
                if(($comment->job_id == 0 || empty($comment->job_id)) && $company)
                {
                    $company->incrementAdd('comments_num',1);
                }
            }catch (\PDOException $e){
                Log::info(['企业评论异常'=>$e->getMessage()]);
                return $this->formatJson('falses','数据异常！');
            }
            $total = count(CompanyComment::where(array('to_comment_id'=>$comment->to_comment_id,'company_id'=>$comment->company_id,'job_id'=>$comment->job_id))->get());
            $totalnum =($comment->to_comment_id > 0) ? $total:0;
            $comment['username'] =getUserName($user->id);
            $comment['logo'] = userlogo($user->id,'middle');
            $comment['replyimg'] = asset('/images/front/jiuyezhinan/pl.png');

            return Response::json(array('msg'=>'成功',
                'status'=>'success',
                'data'=>$comment,
                'total'=>$totalnum
            ));
        }

    }

    /**
     * 课程评论
     */
    private function coursecom()
    {
        $user = Auth::user();
        if(empty($user)){
            return  Response::json(array('msg'=>'请先登录！',
                'status'=>'falses',
            ));
        }
        $comment = new CourseScore;
        $comment->c_id = Input::get('cid',0);
        $courses = Courses::where(['id'=>$comment->c_id])->first();
        if(empty($courses))
            return $this->formatJson('error','参数异常');
        
        $comment->u_id = $user->id;
        $comment->content = Input::get('content');
        $price = Input::get('feiyong',0);
        if(!$price){
            $price = 0;
        }
        $comment->cost = number_format($price, 2, '.', '');
        $comment->score = Input::get('ztpj',0);
        $comment->effect = Input::get('xgpj',0);
        $comment->teachers = Input::get('szpj',0);
        $comment->environment = Input::get('hjpj',0);
        $comment->to_comment_id = Input::get('id',0);
        $comment->to_user_id = Input::get('touid',0);
        //敏感词过滤
        $wordstr = $this->infos['sensitive_words'];
        $comment->content = $this->filterWords(Input::get('content'),$wordstr);
        if(($comment->to_comment_id == 0) && (empty($comment->score)||empty($comment->effect)||empty($comment->teachers)||empty($comment->environment)) ){
                return  Response::json(array('msg'=>'请选择星级评分！',
                    'status'=>'falses',
                ));
        }
//        if(($comment->to_comment_id == 0) && empty($comment->cost)){
//            return  Response::json(array('msg'=>'请填写相关费用！',
//                 'status'=>'falses',
//            ));
//        }
        if(empty($comment->content))
        {
            return  Response::json(array('msg'=>'评论内容不能为空！',
                'status'=>'falses',
            ));
        }else{
            DB::beginTransaction();
            try {
                $comment->save();
                $total = count(CourseScore::where(array('to_comment_id'=>$comment->to_comment_id,'c_id'=>$comment->c_id))->get());
                $totalnum =($comment->to_comment_id > 0) ? $total:0;
                $comment['username'] =getUserName($user->id);
                $comment['logo'] = userlogo($user->id,'middle');
                $comment['replyimg'] = asset('/images/front/jiuyezhinan/pl.png');
                $comment['starcolor'] = asset('/images/front/recommendcourse/star-color.png');
                $comment['star'] = asset('/images/front/recommendcourse/star.png');
                if($comment->to_comment_id == 0){  //一级评分   需计算各个等级平均值
                    $scoreavg = DB::table('course_score')->where('c_id','=',$comment->c_id)->avg('score');
                    $effectavg = DB::table('course_score')->where('c_id','=',$comment->c_id)->avg('effect');
                    $teasavg = DB::table('course_score')->where('c_id','=',$comment->c_id)->avg('teachers');
                    $envavg = DB::table('course_score')->where('c_id','=',$comment->c_id)->avg('environment');
                    $courses->score = $scoreavg;
                    $courses->effect = $effectavg;
                    $courses->teachers = $teasavg;
                    $courses->environment = $envavg;
                    $courses->save();
                }
                $courses->organization->incrementAdd('comments_num',1);
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::info(['机构课程评论异常'=>$e->getMessage()]);
                return $this->formatJson('error','数据异常！');
            }
            return Response::json(array('msg'=>'成功',
                    'status'=>'success',
                    'data'=>$comment,
                    'total'=>$totalnum
            ));

        }
    }

    /**
     * 就业指南详情评论
     */
    private function empcom()
    {
        $user = Auth::user();
        if(empty($user)){
            return  Response::json(array('msg'=>'请先登录！',
                'status'=>'falses',
            ));
        }
        $comment = new EmployComments;
        $comment->employ_id = Input::get('comid',0);
        $comment->content = Input::get('content');
        $comment->user_id = $user->id;
        $comment->to_comment_id = Input::get('cid',0);
        $comment->to_user_id = Input::get('touid',0);
        //敏感词过滤
        $wordstr = $this->infos['sensitive_words'];
        $comment->content = $this->filterWords(Input::get('content'),$wordstr);
        if(empty($comment->content))
        {
            return  Response::json(array('msg'=>'评论内容不能为空！',
                'status'=>'falses',
            ));
        }else{
            DB::beginTransaction();
            try {
                $comment->save();
                $total = count(EmployComments::where(array('to_comment_id'=>$comment->to_comment_id,'employ_id'=>$comment->employ_id))->get());
                $totalnum =($comment->to_comment_id > 0) ? $total:0;
                $comment['username'] =getUserName($user->id);
                $comment['logo'] = userlogo($user->id,'middle');
                $comment['replyimg'] = asset('/images/front/jiuyezhinan/pl.png');

                if($comment->to_comment_id == 0){  //一级评论 增加评论数量
                    $exts = EmployExt::findOrNew($comment->employ_id);
                    $exts->incrementAdd('comment_num',1);
                }
            }catch (\PDOException $e){
                DB::rollback();
            }
            DB::commit();
            return Response::json(array('msg'=>'成功',
                'status'=>'success',
                'data'=>$comment,
                'total'=>$totalnum
            ));

        }
    }

    /**
     * 论坛评论
     */
    private function bbscom()
    {
        $user = Auth::user();
        if(empty($user)){
            return  Response::json(array('msg'=>'请先登录！',
                'status'=>'falses',
            ));
        }
        if(Input::get('type') == 0){ //一级评论
            $comment = new BbsAnswer;
            $comment->question_id = Input::get('qid',0);
            $comment->title = Input::get('content');
            $comment->user_id = $user->id;
            $comment->category_id = Input::get('cateid',0);
            //敏感词过滤
            $wordstr = $this->infos['sensitive_words'];
            $comment->title = $this->filterWords(Input::get('content'),$wordstr);
            if(empty($comment->title))
            {
                return  Response::json(array('msg'=>'评论内容不能为空！',
                    'status'=>'falses',
                ));
            }else{
                DB::beginTransaction();
                try {
                   $comment->save();
                   $comment['username'] =getUserName($user->id);
                   $comment['logo'] = userlogo($user->id,'middle');
                   $comment['replyimg'] = asset('/images/front/jiuyezhinan/pl.png');
                   $bbsq = BbsQuestion::find($comment->question_id);
                   $bbsq->incrementAdd('answer_count',1);
                   $bbsq->incrementAdd('comment_count',1);
                   $bbsq->last_answer = $user->id;
                   $bbsq->answer_count = count($bbsq->answers);
                   $sql = DB::select('SELECT DISTINCT user_id FROM qm_bbs_answer WHERE question_id = '.$comment->question_id);
                   $bbsq->answer_users = count($sql);
                   $bbsq->save();
                }catch (\PDOException $e){
                   DB::rollback();
                }
                DB::commit();
                return Response::json(array('msg'=>'成功',
                        'status'=>'success',
                        'data'=>$comment,
                ));
            }
        }else{ //子评论
            $comment = new BbsAnswerComment;
            $comment->answer_id = Input::get('aid',0);
            $comment->message = Input::get('content');
            $comment->user_id = $user->id;
            //敏感词过滤
            $wordstr = $this->infos['sensitive_words'];
            $comment->message = $this->filterWords(Input::get('content'),$wordstr);
            if(empty($comment->message))
            {
                return  Response::json(array('msg'=>'评论内容不能为空！',
                    'status'=>'falses',
                ));
            }else{
                DB::beginTransaction();
                try {
                    $comment->save();
                    $comment['username'] =getUserName($user->id);
                    $comment['logo'] = userlogo($user->id,'middle');
                    $comment['replyimg'] = asset('/images/front/jiuyezhinan/pl.png');
                    $total = count(BbsAnswerComment::where(array('answer_id'=>$comment->answer_id))->get());
                    $bbsa = BbsAnswer::findOrNew($comment->answer_id);
                    $bbsa->incrementAdd('comment_count',1);
                }catch (\PDOException $e){
                    DB::rollback();
                }
                DB::commit();
                return Response::json(array('msg'=>'成功',
                    'status'=>'success',
                    'data'=>$comment,
                    'total'=>$total
                ));
            }
        }
    }

    /**
     * 职场教程、企业内训 评论
     * 职场：teaches  内训：tcompany
     */
    private function teachescom()
    {
        $user = Auth::user();
        if(empty($user)){
            return  Response::json(array('msg'=>'请先登录！',
                'status'=>'falses',
            ));
        }
         $comment = new Comments;
         $comment->app_table = Input::get('app');
         $comment->app_id = Input::get('appid',0);
         $comment->user_id = $user->id;
         $comment->content = Input::get('content');
         $comment->to_comment_id = Input::get('cid',0);
         $comment->to_user_id = Input::get('touid',0);
         //敏感词过滤
         $wordstr = $this->infos['sensitive_words'];
         $comment->content = $this->filterWords(Input::get('content'),$wordstr);
         if(empty($comment->content))
         {
            return  Response::json(array('msg'=>'评论内容不能为空！',
                    'status'=>'falses',
            ));
         }else{
            DB::beginTransaction();
            try {
                $comment->save();
                $comment['username'] =getUserName($user->id);
                $comment['logo'] = userlogo($user->id,'middle');
                $comment['replyimg'] = asset('/images/front/jiuyezhinan/pl.png');
                $total = count(Comments::where(array('to_comment_id'=>$comment->to_comment_id,'app_table'=>$comment->app_table,'app_id'=>$comment->app_id))->get());
                $totalnum =($comment->to_comment_id > 0) ? $total:0;
                if(($comment->app_table == 'teaches') && ($comment->to_comment_id == 0)){
                    $teac = Teaches::findOrNew($comment->app_id);
                    $teac->incrementAdd('comments_num',1);
                }else if(($comment->app_table == 'tcompany') && ($comment->to_comment_id == 0)){
                    $teac = TeachesCompany::findOrNew($comment->app_id);
                    $teac->incrementAdd('comments_num',1);
                }else if(($comment->app_table == 'tcourse') && ($comment->to_comment_id == 0)){
                    $teac = TeachesContent::findOrNew($comment->app_id);
                    $teac->incrementAdd('comments_num',1);
                }
            }catch (\PDOException $e){
                 DB::rollback();
            }
            DB::commit();
               return Response::json(array('msg'=>'成功',
                     'status'=>'success',
                     'data'=>$comment,
                     'total'=>$totalnum
            ));
         }
    }


}
